package com.wdc.blockingQueue;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 单锁实现
 * @param <E> 元素类型
 */
public class BlockingQueue1<E> implements BlockingQueue<E> {

    private final E[] array ;
    private int head = 0;
    private int tail = 0;
    private int size = 0;

    public BlockingQueue1(int capacity) {
        array = (E[]) new Object[capacity];
    }

    //创建一个锁对象
    private ReentrantLock lock = new ReentrantLock();
    private Condition headWaits = lock.newCondition();
    private Condition tailWaits = lock.newCondition();
    private boolean isEmpty(){
        return size ==0;
    }
    private boolean isFull(){
        return size == array.length;
    }
    @Override
    public void offer(E e) throws InterruptedException {
        lock.lockInterruptibly();
        try{
            while(isFull()) {
                tailWaits.await();
            }

            array[tail] = e;
            if (++tail == array.length){
                tail = 0;
            }
            size++;
            headWaits.signal();
        }finally {
            lock.unlock();
        }

    }

    @Override
    public boolean offer(E e, long timeout) throws InterruptedException {
        lock.lockInterruptibly();
        try{
            long nanos = TimeUnit.MILLISECONDS.toNanos(timeout);  //把传过来的参数转换为纳秒

            while(isFull()) {
                if(nanos <= 0) {
                    return false;
                }
                nanos = tailWaits.awaitNanos(nanos);  //纳秒  方法返回值是剩下的时间
            }

            array[tail] = e;
            if (++tail == array.length){
                tail = 0;
            }
            size++;
            headWaits.signal();
            return true;
        }finally {
            lock.unlock();
        }

    }

    @Override
    public E poll() throws InterruptedException {
        lock.lockInterruptibly();
        try {
            while (isEmpty()){
                headWaits.await();
            }
            E e = array[head];
            array[head] = null;  //help GC
            if (++head == array.length){
                head = 0;
            }
            size--;
            tailWaits.signal();
        }finally {
            lock.unlock();
        }
        return null;
    }
}
